<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/29
 * Time: 11:14
 */
namespace App\Http\Controllers\Api\V6;

use App\Common\ApiData;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Modules\EntBookInfo;
use App\Modules\EntBookImg;
use App\Modules\EntMemberInfo;
use App\Modules\EntBookSumUp;
use App\Modules\EntBookCollect;
use App\Modules\EntBookViewLog;
use Validator, DB;
use PHPMailer;
use App\Models\V6\BookModel;
use App\Models\V6\MemberModel;
use App\Repository\Comment;
use App\Models\V6\ScoreModel;



class BookController extends BaseController
{
    protected $url;
    private $apiData;
    use Comment;

    public function __construct(){
        $this->url      = env('ADMIN_HOST');
        $this->apiData  = new ApiData();
    }

    /**
     * 书籍分类
     *
     */
    public function getBookType()
    {
        $bookModel  = new BookModel();
        $bookTypes  = $bookModel->get_book_types();
        $data = ['message' => 'ok', 'code' => 200, 'booktypelist' => $bookTypes];
        return response()->json($data);
    }




    /**
     * 推荐书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookRecommendList()
    {
        $bookModel  = new BookModel();
        $recommentBooks = $bookModel->get_recomment_books();
        return response()->json(['message' => 'ok', 'code' => 200, 'bookrecommendlist' => $recommentBooks]);
    }




    /**
     * 编辑添加读书改进计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit_read_plan(Request $request)
    {
        $bookId     = $request->input('bookId');
        $userId     = $request->input('userId');
        $upid       = $request->input('readPlanId');
        $bookidea1  = $request->input('book');
        $bookidea2  = $request->input('people');
        $bookidea3  = $request->input('thing');
        $bookidea4  = $request->input('gift');
        //进行敏感词检查
        $res =check_bad_word($bookidea1.$bookidea2.$bookidea3.$bookidea4);
        if(!($res === true)){
            return apiData()->send(2003,"包含敏感词，请检查");
        }
        $bookidea1  = emoji_text_encode($bookidea1);
        $bookidea2  = emoji_text_encode($bookidea2);
        $bookidea3  = emoji_text_encode($bookidea3);
        $bookidea4  = emoji_text_encode($bookidea4);

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);

        if(!$memberInfo)
        {
            return apiData()->send(2004,"请先登录");
        }

        if($upid == 0){
            $sumpInfo = DB::table('booksumup')
                ->where('BookID',$bookId)
                ->where('MemNumber',$memberInfo->MemNumber)
                ->orderBy('SumUpID','DESC')
                ->first();
            if($sumpInfo){
                $upid = $sumpInfo->SumUpID;
            }
        }


        $dateTime   = date_time();
        if ($upid == 0) {   //未添加
            $entBookSumUp = new EntBookSumUp();
            $entBookSumUp->BookID = $bookId;
            $entBookSumUp->MemNumber = $memberInfo->MemNumber;

            //填写读书改进计划加 10 分
            //如果是在24点前填写改进计划，则加分
            $day            = date('w');
            $endTime        = strtotime(date('Y-m-d 23:59:59',time()));
            $integral       = 10;
            if($day == 3 && time() < $endTime) //周三的24点前
            {
                $integral += 10;
                $memberModel->add_member_integral($memberInfo->UserID,$integral,$bookId,"周三24点前完成读书改进计划");

            } else {

                $memberModel->add_member_integral($memberInfo->UserID,$integral,$bookId,"填写读书改进计划");

            }
        } else {    //已经添加过

            $entBookSumUp = EntBookSumUp::find($upid);

        }

        $entBookSumUp->BookReview1 = $bookidea1;
        $entBookSumUp->BookReview2 = $bookidea2;
        $entBookSumUp->BookReview3 = $bookidea3;
        $entBookSumUp->BookReview4 = $bookidea4;
        $entBookSumUp->AddDate     = $dateTime;
        $entBookSumUp->save();

        return apiData()->set_data("sumupId",$entBookSumUp->SumUpID)->send(200,'保存成功');
    }

    /**
     * 收藏书籍
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookCollectStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'id' => 'required',
            'key' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages = [
            'mobile.required' => 2031,
            'id.required' => 2032,
            'key.required' => 2033,
            'timestamp.required' => 2034,
            'sign.required' => 2035
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $id = $request->input('id');
        $timestamp = $request->input('timestamp');
        $sign = $request->input('sign');
        $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);

        if ($v->fails())
        {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        else
        {
            $memNumber = $this->memNumber($mobile, $key);
            if (!$memNumber)
            {
                return response()->json(['message' => "用户不存在", 'code' => 3025]);
            }
        }



        $entBookInfo = EntBookInfo::where('BookID', $id)->where('DeleteMark', 1)->first();
        if ($entBookInfo) {
            $entBookCollect = EntBookCollect::select('ColID')
                ->where('MemNumber', $memNumber->MemNumber)
                ->where('BookID', $id)
                ->first();

            if (!$entBookCollect) {
                $BookCollectStore = new EntBookCollect();
                $BookCollectStore->BookID = $id;
                $BookCollectStore->MemNumber = $memNumber->MemNumber;
                $BookCollectStore->AddDate = date('Y-m-d H:i:s', time());
                $BookCollectStore->save();
                if ($BookCollectStore) {
                    return response()->json(['message' => 'ok', 'code' => 200]);
                } else {
                    return response()->json(['message' => $result, 'code' => 3022]);
                }
            } else {
                EntBookCollect::destroy($entBookCollect->ColID);
                return response()->json(['message' => 'ok', 'code' => 200]);
            }
        } else {
            return response()->json(['message' => $result, 'code' => 3024]);
        }

    }


    /**
     * 返回会员标示
     * @param string $mobile
     * @param string $appkey
     * @return mixed
     */
    protected function memNumber($mobile = '', $appkey = '')
    {
        $entBookInfo = EntMemberInfo::select('UserID','MemNumber', 'MemEndTime', 'States','YourName','email')
            ->where('DeleteMark', 1)
            ->where('AppKey', $appkey)
            ->where('UserName', $mobile)
            ->first();
        return $entBookInfo;
    }



    /**========Ron重新编码==========*/


    /**
     * 书籍详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function book_detail(Request $request)
    {
        //获取书籍详细
        $id             = $request->input('bookId',0);
        $userId         = $request->input('userId',0);

        $bookModel      = new BookModel();
        $bookInfo       = $bookModel->get_book_info($id);
        if($bookInfo == false)
        {
            return apiData()->send(4001,'书籍不存在');
        }
        //获得书籍的评论信息
        $commentNumber = DB::table('comments')
            ->where('lessons_id',$id)
            ->where('deleted_at')
            ->where('type',5)
            ->where('pid',0)
            ->count();

        $bookInfo->commentNumber    = $commentNumber;
        if($bookInfo->article)
        {
            $bookInfo->Description      = $bookInfo->article ;
        }
        else{
            $bookInfo->Description      = url("/home/book_inner?bookId=".$id);
        }

        //获取PPT
        $ppts           = $bookModel->get_book_ppt($id);
        $bookInfo->ppts = $ppts;
        $bookInfo->mp4CurrentTime       = 0;
        $bookInfo->mp3CurrentTime       = 0;
        $bookInfo->mp4TimeId            = 0;
        $bookInfo->mp3TimeId            = 0;

        if($userId > 0){

            $logInfo    = DB::table('media_play_time_log')
                ->where('user_id',$userId)
                ->where(function($db){
                    $db->where('media_type',"lhddmp4")->orWhere('media_type',"lhddmp3");
                })
                ->where('media_id',$bookInfo->BookID)
                ->get();


            if($logInfo){

                foreach($logInfo as $timelog){
                    switch($timelog->media_type){

                        case "lhddmp4":
                                $bookInfo->mp4CurrentTime   = $timelog->current_time;
                                $bookInfo->mp4TimeId        = $timelog->time_id;
                            break;
                        case "lhddmp3":
                                $bookInfo->mp3CurrentTime   = $timelog->current_time;
                                $bookInfo->mp3TimeId        = $timelog->time_id;
                            break;
                    }
                }
            }
        }

        return apiData()
            ->set_data('bookInfo',$bookInfo)
            ->send(200,"ok");

    }

    /**
     * 记录媒体的播放时间
     * */
    public function record_media_time(Request $request){

        $mediaId    = $request->input('mediaId');
        $mediaType  = $request->input('mediaType');
        $currentTime= $request->input("currentTime");
        $userId     = $request->input('userId');
        $timeId     = $request->input('timeId',0);
        $logInfo    = null;
        $table      = "media_play_time_log";
        $timeState  = 5;//5秒钟一个同步时间段
        $updateData = [
            'current_time'  => $currentTime,
            'updated_at'    => date_time()
        ];

        if($timeId == 0){

            $logInfo = DB::table($table)
                ->where('media_type',$mediaType)
                ->where("user_id",$userId)
                ->where("media_id",$mediaId)
                ->first();

            if($logInfo != null){

                $timeId = $logInfo->time_id;
            }
        }

        if($timeId > 0){

            if($logInfo == null){

                $logInfo = DB::table($table)->where('time_id',$timeId)->first();
            }

            $updateData['time_length']  = $logInfo->time_length + $timeState;
            $updateData['time_total']   = $logInfo->time_total  + $timeState; 

            DB::table($table)->where('time_id',$timeId)->update($updateData);

        }else{

            $updateData['user_id']      = $userId;
            $updateData['media_type']   = $mediaType;
            $updateData['media_id']     = $mediaId;
            $updateData['time_length']  = $timeState;
            $updateData['time_total']   = $timeState;

            $timeId     = DB::table($table)->insertGetId($updateData);
        }

        return apiData()->set_data('timeId',$timeId)->send();
    }


    /**
     * 同步学习时间
     * 
     */
    public function sync_lean_time(Request $request){

        $userId     = $request->input('userId');
        
        //这里的起始时间用开始时间倒推
        //1.查找用户是否有记录
        $table      = "media_play_time_log";
        $leanLogs   = DB::table($table)->where('user_id',$userId)->get();

        
        foreach($leanLogs as $leanLog){

            //2.如果时间小于40秒，则不计算,40-60之间，当做一分钟
            $timeLength     = $leanLog->time_length;
            $lastUpTime     = strtotime($leanLog->updated_at);
            $mediaId        = $leanLog->media_id;
            $mediaType      = $leanLog->media_type ?? "";

            if($timeLength < 40 || time() - $lastUpTime < 60 ){ //时间小于40秒和更新时间小于1分钟不进行统计更新
            
                continue;
            }

            $integral   = $timeLength < 60 ? 1 : round($timeLength / 60);        
            $beginTime  = date_time($lastUpTime - $leanLog->time_length);

            //3.清空以往历史
            DB::table($table)->where('time_id',$leanLog->time_id)->update(['time_length'=>0]);

            $nowTime    = date_time();
            
            //4.加入到全局统计中去
            $leanInfo   = [
                "media_type"    => $mediaType,
                "media_id"      => $mediaId,
                "user_id"       => $userId,
                "begin_time"    => $beginTime,
                "end_time"      => $leanLog->updated_at,
                "created_at"    => $nowTime,
                "updated_at"    => $nowTime
            ];

            DB::table('media_play_log')->insert($leanInfo);

            switch($mediaType){

                case "lhddmp3":$note = "听老侯代读";break;
                case "lhddmp4":$note = "看老侯代读";break;
                case 'lhldmp3':$note = "听老侯论道";break;
            }

            //5.加入到积分表中去
            $integralInfo   = [
                "user_id"       => $userId,
                "integral"      => $integral,
                "content_id"    => $mediaId,
                "note"          => $note.$integral."分钟",
                "created_at"    => $nowTime,
                "updated_at"    => $nowTime
            ];
            DB::table('member_integral')->insert($integralInfo);
        }
        
        return apiData()->send();
    }

    /**
     * 获得学习时间
     * */
    public function get_book_learn_time(Request $request){

        $userId     = $request->input('userId');

        $learnTimes = DB::table('media_play_log as a')
            ->leftJoin('bookinfo as b','b.BookID','=','a.media_id')
            ->where('a.user_id',$userId)
            ->where(function($db){
                $db->where('a.media_type','lhddmp3')->orWhere('a.media_type','lhddmp4');
            })
            ->select(DB::raw("sum(a.end_time - a.begin_time) as learn_time"),'b.BookID','b.BookTitle','b.book_img')
            ->groupBy('media_id')
            ->paginate(20);

        foreach($learnTimes as &$learnInfo){

            $learnInfo->book_img    = env('HOST').$learnInfo->book_img;

            if($learnInfo->learn_time < 60){

                $learnInfo->learn_time = $learnInfo->learn_time."秒";

            }else{

                $learnInfo->learn_time = intval($learnInfo->learn_time / 60)."分钟".($learnInfo->learn_time % 60)."秒";
            }
        }

        return apiData()->set_data('learnTimes',$learnTimes)->send();
    }

    public function save_search_keywords($userId,$keywords){

        //检查系统中有没有
        $keyWordsInfo = DB::table('book_search_keywords')
            ->where('keywords',$keywords)
            ->where("user_id",$userId)
            ->first();

        if($keyWordsInfo == null || ($keyWordsInfo && $userId > 0)){

            DB::table('book_search_keywords')->insert(["keywords"=>$keywords,"search_times"=>1,"user_id"=>$userId]);

            //将用户旧的删除了
            if($userId > 0 && $keyWordsInfo){

                DB::table('book_search_keywords')->where('keywords_id',$keyWordsInfo->keywords_id)->delete();
            }

        }elseif($userId == 0){

            DB::table('book_search_keywords')
                ->where("keywords_id",$keyWordsInfo->keywords_id)
                ->increment("search_times");
        }
    }

    public function delete_search_keywords(Request $request){

        $userId = $request->input('userId',0);
        if($userId > 0){

            DB::table('book_search_keywords')->where('user_id',$userId)->delete();
        }

        return apiData()->send();
    }

    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_book_list(Request $request)
    {
        $keyWords       = $request->input('keywords','');
        $userId         = $request->input('userId');

        $bookType       = $request->input('bookTypeId',0);
        $page           = $request->input('page',1);

        //读取所有书籍
        $bookModel      = new BookModel();
        $entBookInfo    = $bookModel->page_book_list('lhdd',2,$keyWords,$bookType);


        //如果有关键字，将关键字存储到系统中

        if($page == 1 && trim($keyWords) != ""){

            $this->save_search_keywords(0,$keyWords);

            if($userId){
                $this->save_search_keywords($userId,$keyWords);
            }
        }

        $imgs = ['c2','c3','c4'];

        foreach ($entBookInfo as $key => $book)
        {
            $book->hasReadPlan  = 0;
            $book->bg_img       = env('HOST')."/".$book->bg_img;
            
            //$book->bg_img_wx    = env('HOST').'/'.default_book_wx_bg($book->bg_img_wx);
            if($page == 1 && $key == 0){
            	$th = "c1";
            }elseif($page ==1){
            	$th 				= $imgs[($key-1)%3];	
            }else{
            	$th 				= $imgs[$key%3];	
            }
            
            $book->bg_img_wx    = url("image/book-bg/{$th}.png");
            $book->topImg       = env('HOST')."/".($book->top_img_wx ? $book->top_img_wx : "image/book-bg/c0.png");
            $book->ReadNumber   = change_read_number($book->ReadNumber);
        }

        return apiData()
            ->set_data('books',$entBookInfo)
            ->send(200,'ok');
    }

    /**
     * 获得已读过的书籍
     * */
    public function get_readed_book_list(Request $request)
    {
        $memNumber      = $request->input('memNumber');

        $bookModel      = new BookModel();
        $books          = $bookModel->get_user_readed_book($memNumber);

        return apiData()
            ->set_data('books',$books)
            ->send(200,'ok');
    }

    /**
     * 获得搜索关键字
     * */
    public function get_search_keywords(Request $request){

        $userId     = $request->input('userId',0);

        //个人历史信息
        if($userId == 0){

            $historyKeywords    = [];

        }else{

            $historyKeywords = DB::table("book_search_keywords")
                ->where('user_id',$userId)
                ->orderBy("keywords_id",'desc')
                ->limit(10)
                ->pluck("keywords");
        }

        //整体历史
        $hotKeywords = DB::table('book_search_keywords')->where('user_id',0)->orderBy("search_times","desc")->limit(20)->pluck("keywords");


        return apiData()->set_data("historyKeywords",$historyKeywords)->set_data("hotKeywords",$hotKeywords)->send();

    }



    /**
     * 读书改进计划
     * */
    public function get_user_read_plan(Request $request)
    {
        $bookId         = $request->input("bookId",0);
        $userId         = $request->input('userId',0);
        $memberNumber   = $request->input('memberNumber',"");
        $bookModel      = new BookModel();

        $readPlan       = $bookModel->get_user_book_read_plan($bookId,$memberNumber);

        return apiData()->set_data("readplan",$readPlan)->send();
    }

    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookList_other(Request $request)
    {
        $friendUserId   = $request->input('friendUserId',0);
        $userId         = $request->input('tokenUserId',0);

        //读取所有书籍
        $bookModel      = new BookModel();
        $entBookInfo    = $bookModel->get_book_list(0,'lhdd');

        foreach ($entBookInfo as $book)
        {
            $book->hasReadPlan = 0;
        }

        define('mem_status_unlogin',3);
        define('mem_status_had_end',1);
        define('mem_status_payed',2);
        define('mem_status_unpay',4);
        $memStatus = mem_status_unlogin;


        $entMemberInfo  = false;
        $memberModel    = new MemberModel();
        if($userId){
            $entMemberInfo = $memberModel->get_member_info_by_id($userId);
        }

        if($entMemberInfo) {
            $memTime    = $entMemberInfo->AddDate;
            $memNumber  = $entMemberInfo->MemNumber;


            //取出该会员所有收藏的书籍
            $collectedBook  = $bookModel->get_member_collected_book($memNumber);
            $colllist       = [];
            foreach($collectedBook as $book){
                array_push($colllist,$book->BookID);
            }


            $readPlanUserMember = $memNumber; //好友的读书改进  如果没有好友 则是自己
            if($friendUserId >0){
                $friendInfo = $memberModel->get_member_info_by_id($friendUserId);
                $readPlanUserMember = $friendInfo->MemNumber;
            }

            //取出已经填写过读书计划的书籍
            $hasWriteReadPlan = DB::table('booksumup')
                ->where('MemNumber',$readPlanUserMember)
                ->distinct()
                ->pluck('BookID')
                ->toArray();
            $hasWriteReadPlan = $hasWriteReadPlan?$hasWriteReadPlan:[];

            //程序调整书籍排列顺序0不显示 1显示
            foreach ($entBookInfo as $book) {
                $bookAddTime    = $book->AddDate;
                $memberAddTime  = $memTime;
                if (strtotime($bookAddTime) > strtotime($memberAddTime)) {
                    $book->IsShow = 0;
                }

                //是否收藏过该书籍 0-否 1-是--MasterID
                $bookId = $book->BookID;
                $book->MasterID     = in_array($bookId, $colllist)?1:0;
                $book->hasReadPlan  = in_array($bookId, $hasWriteReadPlan)?1:0;
            }
        }

        return apiData()
            ->set_data('memstate',$memStatus)
            ->set_data('booklist',$entBookInfo)
            ->send(200,'ok');
    }

    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function free_books(Request $request)
    {
        //读取所有书籍
        $bookModel      = new BookModel();
        $page           = $request->input('page',0);
        $books    = $bookModel->get_book_list($page,'lhdd',1);

        foreach($books as $book)
        {
            $book->bg_img       = env('HOST')."/".$book->bg_img;
            $book->bg_img_wx    = env('HOST').'/'.default_book_wx_bg($book->bg_img_wx);
            $book->Description  = $book->article;
            $book->ReadNumber   = change_read_number($book->ReadNumber);
        }
        return apiData()
            ->set_data('books',$books)
            ->send(200,'ok');
    }



    /**
     * 发送书籍PPT
     * */
    public function send_book_ppt(Request $request){

        $email  = $request->input('email','');
        $bookId = $request->input('bookId','');
        $userId = $request->input('userId',0);

        $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
        $res = preg_match($pattern, $email);
        $apiData= new ApiData();

        if(!$res)
        {
            return $apiData->send(400,"邮箱错误");
        }

        $bookModel  = new BookModel();
        $bookInfo   = $bookModel->get_book_info($bookId);
        $ppts       = $bookModel->get_book_ppt($bookId);

        //Create a new PHPMailer instance
        $mail = new PHPMailer();

        //$file = public_path('uploads/ppt.zip');
        if(empty($bookInfo->ppt)){
            return $apiData->send(2001,'本书籍暂无PPT文件');
        }
        $pptFile   = asset($bookInfo->ppt);

        $content = view('other/email-ppt',['ppts'=>$ppts,'bookInfo'=>$bookInfo,'pptFile'=>$pptFile]);
        //return $content;
        $ext    = explode('.',$bookInfo->ppt);

        $mail->SMTPDebug = 0;
        $mail->IsSMTP(); // 启用SMTP
        $mail->Port = 465;
        //$mail->Host='smtp.sina.cn'; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->Host='ssl://smtp.qq.com'; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = true; //启用smtp认证

        //$mail->Username = 'zhweixi@sina.cn'; //你的邮箱名
        //$mail->Password = 'zhangweixi123' ; //邮箱密码

       // $mail->Username = '3367067598@qq.com'; //你的邮箱名
       // $mail->Password = 'pqmlpzsxufhadbid' ; //邮箱密码
       // $mail->From = '3367067598@qq.com'; //发件人地址（也就是你的邮箱地址）


        $mail->Username = '2053056069@qq.com'; //你的邮箱名
        $mail->Password = 'fpsnegirmmrgcaea'; //邮箱密码
        $mail->From     = '2053056069@qq.com'; //发件人地址（也就是你的邮箱地址）



        $mail->FromName = "教导读书会"; //发件人姓名
        $mail->AddAddress($email,"尊敬的客户");
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(true); // 是否HTML格式邮件
        $mail->CharSet='utf-8'; //设置邮件编码
        $mail->Subject ="书籍《".$bookInfo->BookTitle."》PPT"; //邮件主题
        //$mail->AddAttachment($file,$bookInfo->BookTitle."PPT.".$ext[1]);
        $mail->Body = $content; //邮件内容
        $mail->AltBody = "活动信息"; //邮件正文不支持HTML的备用显示

        $result = $mail->Send();
        if($userId > 0){

            $userInfo   = MemberModel::find($userId);
            $mobile     = $userInfo->UserName;

        }else{

            $mobile     = "";
        }

        $logInfo    = [
            'email'     => $email,
            'book_id'   => $bookId,
            'mobile'    => $mobile,
            'result'    => $mail->ErrorInfo,
            'created_at'=> date_time()
        ];
        DB::table('book_ppt_download_log')->insertGetId($logInfo);

        if($result){

            if($userId > 0){

                $memberModel    = new MemberModel();
                $memberModel->update_member_info(['UserID'=>$userId,'email'=>$email]);
            }

            return $apiData->send(200,'PPT发送成功');
        }

        return $apiData->send(400,$mail->ErrorInfo);
    }



    /**
     * 添加评分
     * */
    public function add_score(Request $request)
    {

        $contentId  = $request->input('contentId');
        $contentType= $request->input('contentType');
        $userId     = $request->input('tokenUserId');
        $score      = $request->input('score');

        $paras      = [
            'contentId' => [$contentId,"缺少内容Id"],
            'contentTy' => [$contentType,'缺少内容类型'],
            'score'     => [$score,'缺少分数']
        ];

        $res    = $this->check_params($paras);
        if($res->status == false)
        {
            return apiData()->send(4001,$res->message);
        }
        $scoreModel = new ScoreModel();
        $scoreModel->add_score($userId,$contentId,$contentType,$score);

        $averageInfo= $scoreModel->get_average_score($contentId,$contentType);
        $score      = $averageInfo->score / $averageInfo->total;
        $score      = number_format($score,1);

        $bookModel  = new BookModel();
        $bookModel->where('BookID',$contentId)->update(['score'=>$score]);
        return apiData()->set_data('score',$score)->send(200,'ok');
    }

    public function book_error(Request $request)
    {
        $params     = $request->all();
        $params     = date_time()."\n".\GuzzleHttp\json_encode($params)."\n";
        file_put_contents(public_path('logs/book-error.log'),$params,FILE_APPEND);
        return \apiData()->send();
    }
}